package org.misty.blog.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null) {
            String requestUri = request.getRequestURI();
            log.debug("正在访问 {}, 需登录", requestUri);
            // 记录当前GET请求页面
            if (request.getMethod().equalsIgnoreCase("get")) {
                log.debug("当前为GET请求，记录请求URI以便登录后自动跳转");
                session.setAttribute("requestUri", requestUri);
            }
            // 跳转到登录页
            response.sendRedirect("/admin");
            return false;
        }
        return true;
    }
}
